<!-- 诊断编辑页面 -->
<template>
  <div class="diagnosis-edit">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="left"
    >
      <!-- 页面标题 -->
      <div class="page-header">
        <h2 class="page-title">
          {{ isActuallyEdit ? "编辑诊断记录" : "新建诊断记录" }}
        </h2>
        <div class="header-actions">
          <el-button @click="handleCancel">取消</el-button>
          <!-- 新增：更新诊断不关闭按钮 -->
          <el-button
            type="primary"
            @click="handleSave(false)"
            :loading="saving"
          >
            {{ isActuallyEdit ? "更新诊断并不关闭" : "保存诊断并不关闭" }}
          </el-button>
          <!-- 修改：更新诊断并关闭按钮 -->
          <el-button type="primary" @click="handleSave(true)" :loading="saving">
            {{ isActuallyEdit ? "更新诊断并关闭" : "保存诊断并关闭" }}
          </el-button>
          <el-button
            type="success"
            @click="handleSaveAndComplete(true)"
            :loading="saving"
            :disabled="!formData.current_diagnosis"
          >
            {{ isActuallyEdit ? "更新并完成" : "保存并完成" }}
          </el-button>
        </div>
      </div>

      <!-- 患者信息 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">患者信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="患者姓名" prop="patient_name">
              <el-input
                v-model="formData.patient_name"
                placeholder="请输入患者姓名"
                :disabled="isActuallyEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="患者年龄" prop="patient_age">
              <el-input-number
                v-model="formData.patient_age"
                :min="0"
                :max="150"
                :disabled="isActuallyEdit"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="患者性别" prop="patient_gender">
              <el-radio-group
                v-model="formData.patient_gender"
                :disabled="isActuallyEdit"
              >
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="8">
            <el-form-item label="记录编号">
              <el-input v-model="formData.record_no" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间">
              <el-input v-model="formData.create_time" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="诊断状态">
              <el-tag
                :type="getStatusType(formData.diagnosis_status)"
                size="small"
              >
                {{ getStatusText(formData.diagnosis_status) }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 主诉和现病史 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">主诉和现病史</span>
            <el-button
              v-if="formData.chief_complaint"
              type="primary"
              link
              @click="handleAISymptomAnalysis"
              :loading="aiLoading.symptom"
            >
              <el-icon><MagicStick /></el-icon>
              AI症状分析
            </el-button>
          </div>
        </template>

        <el-form-item label="主诉" prop="chief_complaint">
          <el-input
            v-model="formData.chief_complaint"
            type="textarea"
            :rows="3"
            placeholder="请输入患者主诉，如：头痛、发热3天"
            maxlength="500"
            show-word-limit
            @blur="onChiefComplaintBlur"
          />
        </el-form-item>

        <el-form-item label="现病史" prop="present_illness">
          <el-input
            v-model="formData.present_illness"
            type="textarea"
            :rows="4"
            placeholder="详细描述疾病发生、发展、诊疗过程"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <!-- AI分析结果 -->
        <div v-if="aiAnalysis.symptomResult" class="ai-analysis-block">
          <el-alert
            title="AI症状分析建议"
            type="info"
            :closable="true"
            @close="aiAnalysis.symptomResult = ''"
            show-icon
          >
            <div class="ai-content">
              {{ aiAnalysis.symptomResult }}
              <div class="ai-actions">
                <el-button
                  type="primary"
                  link
                  @click="applyAISuggestion('symptom')"
                >
                  应用建议
                </el-button>
              </div>
            </div>
          </el-alert>
        </div>
      </el-card>

      <!-- 体格检查 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">体格检查</span>
            <el-button
              v-if="formData.chief_complaint"
              type="primary"
              link
              @click="handleAIPhysicalExam"
              :loading="aiLoading.physicalExam"
            >
              <el-icon><MagicStick /></el-icon>
              AI检查建议
            </el-button>
          </div>
        </template>

        <el-form-item label="检查结果" prop="physical_exam">
          <el-input
            v-model="formData.physical_exam"
            type="textarea"
            :rows="4"
            placeholder="记录体温、血压、心肺听诊等体格检查结果"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <!-- AI体格检查建议 -->
        <div v-if="aiAnalysis.physicalExamResult" class="ai-analysis-block">
          <el-alert
            title="AI体格检查建议"
            type="info"
            :closable="true"
            @close="aiAnalysis.physicalExamResult = ''"
            show-icon
          >
            <div class="ai-content">
              {{ aiAnalysis.physicalExamResult }}
              <div class="ai-actions">
                <el-button
                  type="primary"
                  link
                  @click="applyAISuggestion('physicalExam')"
                >
                  应用建议
                </el-button>
              </div>
            </div>
          </el-alert>
        </div>
      </el-card>

      <!-- 检查开具 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">检查开具</span>
            <div>
              <el-button
                type="primary"
                @click="openExaminationOrder"
                :disabled="!formData.patient_name"
              >
                <el-icon><Plus /></el-icon>
                开具检查项目
              </el-button>
              <el-button
                v-if="formData.chief_complaint || formData.physical_exam"
                type="primary"
                link
                @click="handleAILabSuggest"
                :loading="aiLoading.labSuggest"
              >
                <el-icon><MagicStick /></el-icon>
                AI检查项目推荐
              </el-button>
            </div>
          </div>
        </template>

        <!-- 已开具的检查项目 -->
        <div v-if="examinationOrders.length > 0" class="examination-orders">
          <div class="orders-header">
            <h4>已开具检查项目</h4>
            <div>
              <span class="total-fee">总费用: ¥{{ totalExamFee }}</span>
              <el-button
                type="primary"
                link
                @click="handlePrintExaminationOrder"
              >
                打印检查单
              </el-button>
            </div>
          </div>

          <el-table :data="examinationOrders" size="small" class="orders-table">
            <el-table-column prop="item_name" label="检查项目" width="200" />
            <el-table-column
              prop="operation_department_name"
              label="检查科室"
              width="120"
            />
            <el-table-column prop="standard_price" label="费用" width="100">
              <template #default="{ row }">
                ¥{{ row.standard_price }}
              </template>
            </el-table-column>
            <el-table-column prop="payment_status" label="缴费状态" width="100">
              <template #default="{ row }">
                <el-tag
                  :type="getPaymentStatusType(row.payment_status)"
                  size="small"
                >
                  {{ getPaymentStatusText(row.payment_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="order_status" label="检查状态" width="120">
              <template #default="{ row }">
                <el-tag
                  :type="getOrderStatusType(row.order_status)"
                  size="small"
                >
                  {{ getOrderStatusText(row.order_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="handleViewExamResult(row)"
                  :disabled="row.orderStatus !== 'reported'"
                >
                  查看结果
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleCancelExamOrder(row)"
                  :disabled="row.paymentStatus === 'paid'"
                >
                  取消
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-else class="no-orders">
          <el-empty description="暂无检查项目" :image-size="80">
            <el-button type="primary" @click="openExaminationOrder">
              立即开具检查
            </el-button>
          </el-empty>
        </div>

        <!-- AI检查项目推荐 -->
        <div v-if="aiAnalysis.labSuggestResult" class="ai-analysis-block">
          <el-alert
            title="AI检查项目推荐"
            type="info"
            :closable="true"
            @close="aiAnalysis.labSuggestResult = ''"
            show-icon
          >
            <div class="ai-content">
              {{ aiAnalysis.labSuggestResult }}
              <div class="ai-actions">
                <el-button
                  type="primary"
                  link
                  @click="applyAISuggestion('labSuggest')"
                >
                  应用建议
                </el-button>
                <el-button type="success" link @click="applyAndCreateExamOrder">
                  应用并开具检查
                </el-button>
              </div>
            </div>
          </el-alert>
        </div>
      </el-card>

      <!-- 辅助检查结果 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">辅助检查结果</span>
          </div>
        </template>

        <el-form-item label="检查结果汇总" prop="lab_results">
          <el-input
            v-model="formData.lab_results"
            type="textarea"
            :rows="3"
            placeholder="记录实验室检查、影像学检查等结果"
            maxlength="800"
            show-word-limit
          />
        </el-form-item>

        <!-- 文件上传 -->
        <el-form-item label="检查报告">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="text"
            :auto-upload="false"
            :on-remove="handleFileRemove"
            :on-change="handleFileChange"
            :before-upload="beforeFileUpload"
          >
            <el-button type="primary">
              <el-icon><Plus /></el-icon>
              上传检查报告
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片、PDF等格式文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-card>

      <!-- 诊断结果 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">诊断结果</span>
            <el-button
              v-if="showAIDiagnosis"
              type="primary"
              link
              @click="handleAIDiagnosis"
              :loading="aiLoading.diagnosis"
            >
              <el-icon><MagicStick /></el-icon>
              AI辅助诊断
            </el-button>
          </div>
        </template>

        <el-form-item label="初步诊断" prop="preliminary_diagnosis">
          <el-input
            v-model="formData.preliminary_diagnosis"
            placeholder="请输入初步诊断"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="最终诊断" prop="current_diagnosis">
          <el-input
            v-model="formData.current_diagnosis"
            placeholder="请输入最终诊断"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- AI诊断建议 -->
        <div v-if="aiAnalysis.diagnosisResult" class="ai-analysis-block">
          <el-alert
            title="AI诊断建议"
            type="info"
            :closable="true"
            @close="aiAnalysis.diagnosisResult = ''"
            show-icon
          >
            <div class="ai-content">
              {{ aiAnalysis.diagnosisResult }}
              <div class="ai-actions">
                <el-button
                  type="primary"
                  link
                  @click="applyAISuggestion('diagnosis')"
                >
                  应用建议
                </el-button>
              </div>
            </div>
          </el-alert>
        </div>
      </el-card>

      <!-- 治疗建议 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">治疗建议</span>
            <el-button
              v-if="showAITreatment"
              type="primary"
              link
              @click="handleAITreatment"
              :loading="aiLoading.treatment"
            >
              <el-icon><MagicStick /></el-icon>
              AI治疗方案
            </el-button>
          </div>
        </template>

        <el-form-item label="治疗方案" prop="treatment_plan">
          <el-input
            v-model="formData.treatment_plan"
            type="textarea"
            :rows="4"
            placeholder="详细描述治疗方案、用药建议、注意事项等"
            maxlength="1500"
            show-word-limit
          />
        </el-form-item>

        <!-- AI治疗建议 -->
        <div v-if="aiAnalysis.treatmentResult" class="ai-analysis-block">
          <el-alert
            title="AI治疗建议"
            type="info"
            :closable="true"
            @close="aiAnalysis.treatmentResult = ''"
            show-icon
          >
            <div class="ai-content">
              {{ aiAnalysis.treatmentResult }}
              <div class="ai-actions">
                <el-button
                  type="primary"
                  link
                  @click="applyAISuggestion('treatment')"
                >
                  应用建议
                </el-button>
                <el-button
                  type="success"
                  link
                  @click="handleCreatePrescription"
                >
                  开具处方
                </el-button>
              </div>
            </div>
          </el-alert>
        </div>
      </el-card>

      <!-- 快速AI分析面板 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">AI智能辅助</span>
          </div>
        </template>

        <div class="ai-quick-actions">
          <el-button
            type="primary"
            :loading="aiLoading.quickAnalysis"
            :disabled="!formData.chief_complaint"
            @click="handleQuickAnalysis"
          >
            <el-icon><MagicStick /></el-icon>
            一键智能分析
          </el-button>
          <span class="quick-tip"
            >基于主诉自动生成症状分析、诊断建议和治疗方案</span
          >
        </div>

        <!-- 一键分析结果 -->
        <div v-if="aiAnalysis.quickResult" class="ai-analysis-block">
          <el-alert
            title="AI智能分析结果"
            type="success"
            :closable="true"
            @close="aiAnalysis.quickResult = null"
            show-icon
          >
            <div class="ai-content">
              <div class="quick-result-section">
                <h4>💡 症状分析</h4>
                <p>{{ aiAnalysis.quickResult.symptomAnalysis }}</p>
              </div>
              <div class="quick-result-section">
                <h4>🩺 诊断建议</h4>
                <p>{{ aiAnalysis.quickResult.diagnosisSuggest }}</p>
              </div>
              <div class="quick-result-section">
                <h4>💊 治疗方案</h4>
                <p>{{ aiAnalysis.quickResult.treatmentPlan }}</p>
              </div>
              <div class="ai-actions">
                <el-button type="primary" @click="applyQuickAnalysisResult">
                  应用所有建议
                </el-button>
              </div>
            </div>
          </el-alert>
        </div>
      </el-card>
    </el-form>

    <!-- 检查开具对话框 -->
    <el-dialog
      v-model="examOrderDialogVisible"
      :title="`为 ${formData.patient_name} 开具检查项目`"
      width="800px"
    >
      <ExaminationOrderForm
        v-if="examOrderDialogVisible"
        :patient-info="{
          name: formData.patient_name,
          age: formData.patient_age,
          gender: formData.patient_gender,
          insurance_card_number: patientInfo.insurance_card_number,
        }"
        :diagnosis-id="props.recordId"
        :diagnosis-record="formData"
        @close="examOrderDialogVisible = false"
        @saved="handleExamOrderSaved"
      />
    </el-dialog>

    <!-- 检查结果查看对话框 -->
    <el-dialog
      v-model="examResultDialogVisible"
      title="检查结果详情"
      width="70%"
    >
      <div v-if="currentExamResult" class="exam-result-detail">
        <div class="exam-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="检查项目">{{
              currentExamResult.examName
            }}</el-descriptions-item>
            <el-descriptions-item label="检查科室">{{
              currentExamResult.department
            }}</el-descriptions-item>
            <el-descriptions-item label="申请时间">{{
              currentExamResult.applyTime
            }}</el-descriptions-item>
            <el-descriptions-item label="报告时间">{{
              currentExamResult.reportTime
            }}</el-descriptions-item>
            <el-descriptions-item label="检查医生">{{
              currentExamResult.examDoctor
            }}</el-descriptions-item>
            <el-descriptions-item label="审核医生">{{
              currentExamResult.reviewDoctor
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="exam-content">
          <h4>检查所见</h4>
          <div class="exam-findings">{{ currentExamResult.findings }}</div>

          <h4>诊断意见</h4>
          <div class="exam-conclusion">{{ currentExamResult.conclusion }}</div>

          <h4>检查图像</h4>
          <div
            class="exam-images"
            v-if="
              currentExamResult.images && currentExamResult.images.length > 0
            "
          >
            <div
              v-for="(image, index) in currentExamResult.images"
              :key="index"
              class="exam-image-item"
            >
              <el-image
                :src="image"
                :preview-src-list="currentExamResult.images"
                fit="cover"
              />
            </div>
          </div>
          <div v-else class="no-images">暂无检查图像</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, MagicStick, User } from "@element-plus/icons-vue";
import ExaminationOrderForm from "./ExaminationOrderForm.vue";
// 引入封装的AI服务
import aiService from "@/utils/aiService";
// 引入API接口
import {
  getDiagnosisRecordByVisitId,
  getDiagnosisRecordDetailByRecordNo,
  saveDiagnosisRecord,
  getExamOrderByVisitId,
  deleteExamOrderItem,
} from "@/api/doctor";

const props = defineProps({
  recordId: {
    type: [String, Number],
    default: null,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  patientInfo: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["close", "saved"]);

// 表单引用
const formRef = ref();
const saving = ref(false);
// 添加本地状态
const localIsEdit = ref(props.isEdit);

// AI加载状态
const aiLoading = reactive({
  symptom: false,
  physicalExam: false,
  labSuggest: false,
  diagnosis: false,
  treatment: false,
  quickAnalysis: false,
});

// 表单数据
const formData = reactive({
  patient_name: "",
  patient_age: null,
  patient_gender: "男",
  chief_complaint: "",
  present_illness: "",
  physical_exam: "",
  lab_results: "",
  preliminary_diagnosis: "",
  current_diagnosis: "",
  treatment_plan: "",
  status: "in_progress",
  record_no: "",
  create_time: "",
  update_time: "",
  doctor_name: "张医生",
  department: "内科",
});

// 文件列表
const fileList = ref([]);

// AI分析结果
const aiAnalysis = reactive({
  symptomResult: "",
  physicalExamResult: "",
  labSuggestResult: "",
  diagnosisResult: "",
  treatmentResult: "",
  quickResult: null,
});

// 检查订单相关
const examinationOrders = ref([]);
const examOrderDialogVisible = ref(false);
const examResultDialogVisible = ref(false);
const currentExamResult = ref(null);

// 状态映射
const statusMap = {
  pending: { text: "待诊断", type: "warning" },
  in_progress: { text: "诊断中", type: "primary" },
  completed: { text: "已完成", type: "success" },
};

// 缴费状态映射
const paymentStatusMap = {
  pending: { text: "待缴费", type: "warning" },
  paid: { text: "已缴费", type: "success" },
  refunded: { text: "已退款", type: "info" },
};

// 检查订单状态映射
const orderStatusMap = {
  created: { text: "已开具", type: "info" },
  paid: { text: "已缴费", type: "primary" },
  waiting: { text: "待检查", type: "success" },
  in_progress: { text: "检查中", type: "warning" },
  completed: { text: "检查完成", type: "success" },
  reported: { text: "已出报告", type: "success" },
  cancelled: { text: "已取消", type: "danger" },
};

// 检查状态映射
const examStatusMap = {
  pending: { text: "待缴费", type: "warning" },
  paid: { text: "已缴费", type: "info" },
  in_progress: { text: "检查中", type: "primary" },
  completed: { text: "已完成", type: "success" },
  reported: { text: "已出报告", type: "success" },
};

// 表单验证规则
const formRules = {
  patient_name: [
    { required: true, message: "请输入患者姓名", trigger: "blur" },
  ],
  patient_age: [{ required: true, message: "请输入患者年龄", trigger: "blur" }],
  patient_gender: [
    { required: true, message: "请选择患者性别", trigger: "change" },
  ],
  chief_complaint: [{ required: true, message: "请输入主诉", trigger: "blur" }],
};

// 计算属性
const showAIDiagnosis = computed(() => {
  return formData.chief_complaint && formData.physical_exam;
});

const showAITreatment = computed(() => {
  return formData.current_diagnosis || formData.preliminary_diagnosis;
});

const totalExamFee = computed(() => {
  return examinationOrders.value.reduce(
    (total, order) => total + (order.standard_price || 0),
    0
  );
});

// 方法
const getStatusText = (status) => {
  return statusMap[status]?.text || status;
};

const getStatusType = (status) => {
  return statusMap[status]?.type || "info";
};

const getPaymentStatusText = (status) => {
  return paymentStatusMap[status]?.text || status;
};

const getPaymentStatusType = (status) => {
  return paymentStatusMap[status]?.type || "info";
};

const getOrderStatusText = (status) => {
  return orderStatusMap[status]?.text || status;
};

const getOrderStatusType = (status) => {
  return orderStatusMap[status]?.type || "info";
};

const getExamStatusText = (status) => {
  return examStatusMap[status]?.text || status;
};

const getExamStatusType = (status) => {
  return examStatusMap[status]?.type || "info";
};

// 从身份证号计算性别
const calculateGenderFromID = (idNumber) => {
  if (!idNumber || idNumber.length !== 18) {
    return "未知";
  }
  // 获取第17位数字（性别位）
  const genderDigit = parseInt(idNumber.charAt(16));
  // 奇数为男性，偶数为女性
  return genderDigit % 2 === 1 ? "男" : "女";
};

// 从身份证号计算年龄
const calculateAgeFromID = (idNumber) => {
  if (!idNumber || idNumber.length !== 18) {
    return null;
  }

  try {
    // 提取出生年月日
    const birthYear = parseInt(idNumber.substring(6, 10));
    const birthMonth = parseInt(idNumber.substring(10, 12)) - 1; // 月份从0开始
    const birthDay = parseInt(idNumber.substring(12, 14));

    const birthDate = new Date(birthYear, birthMonth, birthDay);
    const today = new Date();

    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();

    // 如果当前月份小于出生月份，或者月份相同但日期小于出生日期，则年龄减1
    if (
      monthDiff < 0 ||
      (monthDiff === 0 && today.getDate() < birthDate.getDate())
    ) {
      age--;
    }

    return age; // 返回数值而不是字符串
  } catch (error) {
    console.error("计算年龄出错:", error);
    return null;
  }
};

// 可以添加一个计算属性来更精确地判断是否是编辑模式
// 修改计算属性
const isActuallyEdit = computed(() => {
  return localIsEdit.value || !!props.patientInfo?.visit_id;
});

/***********************************
 * 加载诊断数据 - 混合方式加载数据
 * *********************************
 */
const loadData = async () => {
  const visitId = props.patientInfo?.visit_id;

  // 情况1：有visit_id，优先从API加载确保数据最新
  if (visitId) {
    try {
      // console.log("通过visit_id从API加载数据:", visitId);
      const response = await getDiagnosisRecordByVisitId({ visit_id: visitId });
      // console.log("诊断详情响应:", response);

      if (response && response.code == 200) {
        const data = response.data || {};

        // 关键修改：不要覆盖患者基本信息，只更新诊断相关字段
        const preserveFields = [
          "patient_name",
          "patient_age",
          "patient_gender",
          "id_number",
        ];
        Object.keys(data).forEach((key) => {
          // 跳过患者基本信息字段，这些应该从props.patientInfo获取
          if (!preserveFields.includes(key)) {
            formData[key] = data[key];
          }
        });

        // 根据身份证号计算年龄和性别
        if (data.id_number) {
          formData.patient_gender = calculateGenderFromID(data.id_number);
          formData.patient_age = calculateAgeFromID(data.id_number);
        }

        // 加载检查项目订单
        await loadExaminationOrders();
        return;
      }
    } catch (error) {
      console.error("通过API加载诊断数据失败:", error);
      ElMessage.warning("从服务器加载数据失败，使用本地数据");
    }
  }

  // 情况2：有recordId但无patientInfo，通过recordId加载
  if (props.recordId && !props.patientInfo) {
    // TODO: 如果需要，可以通过recordId加载数据的逻辑
    const response = await getDiagnosisRecordDetailByRecordNo({
      diagnosis_id: props.recordId,
    });

    if (response && response.code == 200) {
      const data = response.data || {};
      Object.assign(formData, data);

      // 根据身份证号计算年龄和性别
      if (data.id_number) {
        formData.patient_gender = calculateGenderFromID(data.id_number);
        formData.patient_age = calculateAgeFromID(data.id_number);
      }

      console.log("recordId数据加载成功");
    }
  }

  // 情况3：如果没有visit_id但有patientInfo，也尝试加载检查订单
  if (props.patientInfo && !visitId) {
    await loadExaminationOrders();
  }
};

// 加载检查项目订单
const loadExaminationOrders = async () => {
  try {
    const visitId = props.patientInfo?.visit_id;
    if (!visitId) return;

    // TODO: API - 获取检查订单列表
    const response = await getExamOrderByVisitId({ visit_id: visitId });

    if (response && response.code == 200) {
      // 修复：处理返回的数据结构
      const orderData = response.data;
      if (orderData && orderData.order_items) {
        // 将订单项转换为前端期望的格式
        examinationOrders.value = orderData.order_items.map((item) => ({
          order_id: orderData.order_id, // 这里使用父订单的 order_id
          order_no: orderData.order_no,
          item_id: item.item_id,
          item_name: item.exam_name, // 映射字段名
          operation_department_name: item.department_name, // 映射字段名
          standard_price: item.unit_price, // 映射字段名
          // 关键修改：使用项目级别的状态，如果不存在则使用订单状态
          payment_status: item.payment_status,
          order_status: item.order_status,
          // 保留其他可能需要显示的字段
          exam_category: item.exam_category,
          description: item.description,
          item_status: item.item_status,
          result_status: item.result_status,
        }));
      } else {
        examinationOrders.value = [];
      }
    }
  } catch (error) {
    console.error("加载检查订单失败:", error);
  }
};

// 主诉失去焦点时自动触发AI分析
const onChiefComplaintBlur = () => {
  if (formData.chief_complaint && !props.isEdit) {
    // 自动触发症状分析
    // handleAISymptomAnalysis();
  }
};

// ============= AI症状分析 ===============
const handleAISymptomAnalysis = async () => {
  //更改状态
  aiLoading.symptom = true;
  aiAnalysis.symptomResult = "";
  try {
    const messages = [
      aiService.getMedicalSystemPrompt(),
      {
        role: "user",
        content: `请对以下患者主诉进行症状分析：

患者信息：
- 年龄：${formData.patient_age || "未知"}岁
- 性别：${formData.patient_gender}

主诉：${formData.chief_complaint}
现病史：${formData.present_illness || "未提供"}

请分析：
1. 可能的病因和病理机制
2. 需要重点关注的症状特征
3. 紧急程度评估
4. 需要进一步询问的病史要点

请用简洁专业的语言回答。字数不超过500字。`,
      },
    ];

    console.log(messages);

    //调用AI接口
    await aiService.callAIStream(messages, {
      onChunk: (chunk, fullContent) => {
        aiAnalysis.symptomResult = fullContent;
      },
    });

    ElMessage.success("AI症状分析完成");
  } catch (error) {
    console.error("AI症状分析失败:", error);
    ElMessage.error("AI症状分析失败");
  } finally {
    aiLoading.symptom = false;
  }
};

// AI体格检查建议
const handleAIPhysicalExam = async () => {
  if (!formData.chief_complaint) {
    ElMessage.warning("请先填写主诉");
    return;
  }

  aiLoading.physicalExam = true;
  aiAnalysis.physicalExamResult = "";

  try {
    const messages = [
      aiService.getMedicalSystemPrompt(),
      {
        role: "user",
        content: `请根据以下患者情况提供体格检查建议：

患者信息：
- 年龄：${formData.patient_age || "未知"}岁
- 性别：${formData.patient_gender}

主诉：${formData.chief_complaint}
现病史：${formData.present_illness || "未提供"}

请建议：
1. 重点检查的生命体征项目
2. 系统体格检查的重点部位
3. 特殊的专科检查方法
4. 检查时的注意事项

请用简洁专业的语言回答。字数不超过500字。`,
      },
    ];

    await aiService.callAIStream(messages, {
      onChunk: (chunk, fullContent) => {
        aiAnalysis.physicalExamResult = fullContent;
      },
    });

    ElMessage.success("AI体格检查建议完成");
  } catch (error) {
    console.error("AI体格检查建议失败:", error);
    ElMessage.error("AI体格检查建议失败");
  } finally {
    aiLoading.physicalExam = false;
  }
};

// AI检查项目推荐
const handleAILabSuggest = async () => {
  if (!formData.chief_complaint) {
    ElMessage.warning("请先填写主诉");
    return;
  }

  aiLoading.labSuggest = true;
  aiAnalysis.labSuggestResult = "";

  try {
    const messages = [
      aiService.getMedicalSystemPrompt(),
      {
        role: "user",
        content: `请根据以下患者情况推荐检查项目：

患者信息：
- 年龄：${formData.patient_age || "未知"}岁
- 性别：${formData.patient_gender}

主诉：${formData.chief_complaint}
现病史：${formData.present_illness || "未提供"}
体格检查：${formData.physical_exam || "未提供"}
检查项目：${"未提供"}

请推荐：
1. 必要的实验室检查项目
2. 影像学检查建议
3. 特殊检查项目
4. 检查项目的优先级排序

请用简洁专业的语言回答，并说明每个检查项目的临床意义。字数不超过500字。`,
      },
    ];

    await aiService.callAIStream(messages, {
      onChunk: (chunk, fullContent) => {
        aiAnalysis.labSuggestResult = fullContent;
      },
    });

    ElMessage.success("AI检查项目推荐完成");
  } catch (error) {
    console.error("AI检查项目推荐失败:", error);
    ElMessage.error("AI检查项目推荐失败");
  } finally {
    aiLoading.labSuggest = false;
  }
};

// AI辅助诊断
const handleAIDiagnosis = async () => {
  if (!formData.chief_complaint) {
    ElMessage.warning("请先填写主诉");
    return;
  }

  aiLoading.diagnosis = true;
  aiAnalysis.diagnosisResult = "";

  try {
    const messages = [
      aiService.getMedicalSystemPrompt(),
      {
        role: "user",
        content: `请根据以下患者信息提供诊断建议：

患者信息：
- 年龄：${formData.patient_age || "未知"}岁
- 性别：${formData.patient_gender}

主诉：${formData.chief_complaint}
现病史：${formData.present_illness || "未提供"}
体格检查：${formData.physical_exam || "未提供"}
辅助检查：${formData.lab_results || "未提供"}

请提供：
1. 可能的诊断（按可能性排序）
2. 鉴别诊断要点
3. 确诊需要的进一步检查
4. 诊断依据和排除标准

请用简洁专业的语言回答。字数不超过500字。`,
      },
    ];

    await aiService.callAIStream(messages, {
      onChunk: (chunk, fullContent) => {
        aiAnalysis.diagnosisResult = fullContent;
      },
    });

    ElMessage.success("AI辅助诊断完成");
  } catch (error) {
    console.error("AI辅助诊断失败:", error);
    ElMessage.error("AI辅助诊断失败");
  } finally {
    aiLoading.diagnosis = false;
  }
};

// AI治疗方案
const handleAITreatment = async () => {
  if (!formData.current_diagnosis && !formData.preliminary_diagnosis) {
    ElMessage.warning("请先填写诊断结果");
    return;
  }

  aiLoading.treatment = true;
  aiAnalysis.treatmentResult = "";

  try {
    const messages = [
      aiService.getMedicalSystemPrompt(),
      {
        role: "user",
        content: `请根据以下患者信息提供治疗方案：

患者信息：
- 年龄：${formData.patient_age || "未知"}岁
- 性别：${formData.patient_gender}

诊断：${formData.current_diagnosis || formData.preliminary_diagnosis}
主诉：${formData.chief_complaint}
现病史：${formData.present_illness || "未提供"}
辅助检查：${formData.lab_results || "未提供"}

请提供：
1. 治疗原则和目标
2. 具体的治疗方案（药物、剂量、用法）
3. 非药物治疗建议
4. 随访计划和注意事项
5. 可能的并发症及处理

请用简洁专业的语言回答。字数不超过800字。`,
      },
    ];

    await aiService.callAIStream(messages, {
      onChunk: (chunk, fullContent) => {
        aiAnalysis.treatmentResult = fullContent;
      },
    });

    ElMessage.success("AI治疗方案生成完成");
  } catch (error) {
    console.error("AI治疗方案生成失败:", error);
    ElMessage.error("AI治疗方案生成失败");
  } finally {
    aiLoading.treatment = false;
  }
};

// 一键智能分析
const handleQuickAnalysis = async () => {
  if (!formData.chief_complaint) {
    ElMessage.warning("请先填写主诉");
    return;
  }

  aiLoading.quickAnalysis = true;
  aiAnalysis.quickResult = null;

  try {
    const messages = [
      aiService.getMedicalSystemPrompt(),
      {
        role: "user",
        content: `请对以下患者情况进行全面分析：

患者信息：
- 年龄：${formData.patient_age || "未知"}岁
- 性别：${formData.patient_gender}

主诉：${formData.chief_complaint}
现病史：${formData.present_illness || "未提供"}

请提供以下三个方面的分析：

【症状分析】
- 可能的病因分析
- 症状特征解读
- 紧急程度评估

【诊断建议】  
- 可能的诊断方向
- 鉴别诊断要点
- 确诊建议

【治疗方案】
- 治疗原则
- 具体治疗建议
- 随访计划

请用简洁专业的语言分三个部分回答。`,
      },
    ];

    const result = await aiService.callAISimple(messages);

    // 解析结果（简单按段落分割）
    const sections = result.split(/\n\n+/);
    aiAnalysis.quickResult = {
      symptomAnalysis: sections[0] || result,
      diagnosisSuggest: sections[1] || "",
      treatmentPlan: sections[2] || "",
    };

    ElMessage.success("AI智能分析完成");
  } catch (error) {
    console.error("AI一键分析失败:", error);
    ElMessage.error("AI一键分析失败");
  } finally {
    aiLoading.quickAnalysis = false;
  }
};

// 应用AI建议
const applyAISuggestion = (type) => {
  switch (type) {
    case "symptom":
      if (aiAnalysis.symptomResult) {
        formData.present_illness +=
          (formData.present_illness ? "\n\n" : "") + aiAnalysis.symptomResult;
        aiAnalysis.symptomResult = "";
        ElMessage.success("症状分析建议已应用");
      }
      break;
    case "physicalExam":
      if (aiAnalysis.physicalExamResult) {
        formData.physical_exam +=
          (formData.physical_exam ? "\n\n" : "") +
          aiAnalysis.physicalExamResult;
        aiAnalysis.physicalExamResult = "";
        ElMessage.success("体格检查建议已应用");
      }
      break;
    case "labSuggest":
      if (aiAnalysis.labSuggestResult) {
        formData.lab_results +=
          (formData.lab_results ? "\n\n" : "") + aiAnalysis.labSuggestResult;
        aiAnalysis.labSuggestResult = "";
        ElMessage.success("检查项目建议已应用");
      }
      break;
    case "diagnosis":
      if (aiAnalysis.diagnosisResult) {
        formData.preliminary_diagnosis +=
          (formData.preliminary_diagnosis ? "\n\n" : "") +
          aiAnalysis.diagnosisResult;
        aiAnalysis.diagnosisResult = "";
        ElMessage.success("诊断建议已应用");
      }
      break;
    case "treatment":
      if (aiAnalysis.treatmentResult) {
        formData.treatment_plan +=
          (formData.treatment_plan ? "\n\n" : "") + aiAnalysis.treatmentResult;
        aiAnalysis.treatmentResult = "";
        ElMessage.success("治疗方案已应用");
      }
      break;
  }
};

// 应用并创建检查订单
const applyAndCreateExamOrder = () => {
  // formData.lab_results = aiAnalysis.labSuggestResult;
  applyAISuggestion("labSuggest");
  openExaminationOrder();
};

// 应用一键分析结果
const applyQuickAnalysisResult = () => {
  if (aiAnalysis.quickResult) {
    formData.present_illness +=
      (formData.present_illness ? "\n\n" : "") +
      aiAnalysis.quickResult.symptomAnalysis;
    formData.preliminary_diagnosis +=
      (formData.preliminary_diagnosis ? "\n\n" : "") +
      aiAnalysis.quickResult.diagnosisSuggest;
    formData.treatment_plan +=
      (formData.treatment_plan ? "\n\n" : "") +
      aiAnalysis.quickResult.treatmentPlan;

    aiAnalysis.quickResult = null;
    ElMessage.success("所有AI建议已应用");
  }
};

// 打开检查开具对话框
const openExaminationOrder = () => {
  if (!formData.patient_name) {
    ElMessage.warning("请先填写患者信息");
    return;
  }
  examOrderDialogVisible.value = true;
};

// 处理检查订单保存
const handleExamOrderSaved = (newOrders) => {
  console.log("接收到的检查订单数据:", newOrders); // 调试用
  //这里建议直接重新加载检查订单列表，确保数据一致性
  loadExaminationOrders();
  // examinationOrders.value.push(...newOrders); //这里是加载显示
  examOrderDialogVisible.value = false;
  // ElMessage.success("检查项目开具成功");
};

// 查看检查结果
const handleViewExamResult = (order) => {
  // TODO: API - 获取检查结果详情
  // const response = await examinationApi.getExamResult(order.id)
  // currentExamResult.value = response.data

  // 模拟数据
  // currentExamResult.value = {
  //   examName: order.examName,
  //   department: order.department,
  //   applyTime: order.applyTime,
  //   reportTime: order.reportTime,
  //   examDoctor: "李医生",
  //   reviewDoctor: "王主任",
  //   findings: "双侧肺野清晰，肺纹理正常，心影大小形态正常，膈肌光滑。",
  //   conclusion: "胸部X线检查未见明显异常",
  //   images: [
  //     "https://via.placeholder.com/300x400/4A90E2/FFFFFF?text=X-Ray+Image",
  //   ],
  // };

  examResultDialogVisible.value = true;
};

/**
 * 取消检查订单
 * 已经正确修复
 * */
const handleCancelExamOrder = async (orderItem) => {
  try {
    // 检查是否允许取消
    if (orderItem.payment_status === "paid") {
      ElMessage.warning("该项目已缴费，无法取消");
      return;
    }

    await ElMessageBox.confirm(
      `确定要取消检查项目"${orderItem.item_name}"吗？`,
      "取消检查",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    //取消子项目请求
    const params = {
      order_id: orderItem.order_id,
      item_id: orderItem.item_id,
      insurance_card_number: props.patientInfo.insurance_card_number, //已正确添加和执行
    };

    const response = await deleteExamOrderItem(params);

    if (response && response.code === 200) {
      // 更新本地状态为已取消
      loadExaminationOrders();
      ElMessage.success("检查项目已取消");
    } else {
      ElMessage.error(response.msg || "取消检查项目失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消检查订单失败:", error);
      ElMessage.error("取消检查订单失败");
    }
  }
};

// 打印检查单
const handlePrintExaminationOrder = () => {
  ElMessage.info("打印检查单功能开发中");
  // TODO: 实现打印功能
};

// 创建处方
const handleCreatePrescription = () => {
  ElMessage.info("开具处方功能开发中");
  // TODO: 实现处方开具功能
};

// 文件上传处理
const handleFileRemove = (file, fileList) => {
  console.log("文件已移除:", file);
};

const handleFileChange = (file, fileList) => {
  console.log("文件列表变化:", fileList);
};

const beforeFileUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error("文件大小不能超过10MB");
    return false;
  }
  return true;
};

// 保存诊断记录
const handleSave = async (shouldClose = false) => {
  try {
    await formRef.value.validate();
    saving.value = true;

    // 准备保存的数据
    const saveData = {
      ...formData,
      //examination_orders: examinationOrders.value, 这里申请检查项目order_id关联诊断
      attachments: fileList.value,
    };

    // 修复：如果是新建记录，保存成功后设置为编辑状态
    if (!props.isEdit && !localIsEdit.value) {
      localIsEdit.value = true;
    }

    // 调用保存接口
    const response = await saveDiagnosisRecord(saveData);

    ElMessage.success("诊断记录保存成功");
    // 提交是否关闭
    emit("saved", response.data, shouldClose);
  } catch (error) {
    console.error("保存诊断记录失败:", error);
    if (error.errors) {
      // 表单验证错误
      ElMessage.warning("请完善表单信息");
    } else {
      ElMessage.error("保存诊断记录失败");
    }
  } finally {
    saving.value = false;
  }
};

// 保存并完成
const handleSaveAndComplete = async (shouldClose = false) => {
  try {
    await formRef.value.validate();

    if (!formData.current_diagnosis) {
      ElMessage.warning("请填写最终诊断");
      return;
    }

    saving.value = true;

    // 准备保存的数据，设置状态为已完成
    const saveData = {
      ...formData,
      visit_status: "completed",
      diagnosis_status: "completed",
      examination_orders: examinationOrders.value,
      attachments: fileList.value,
    };

    // 调用保存接口
    const response = await saveDiagnosisRecord(saveData);

    ElMessage.success("诊断记录已完成");
    emit("saved", response.data, shouldClose);
  } catch (error) {
    console.error("保存诊断记录失败:", error);
    if (error.errors) {
      ElMessage.warning("请完善表单信息");
    } else {
      ElMessage.error("保存诊断记录失败");
    }
  } finally {
    saving.value = false;
  }
};

// 取消编辑
const handleCancel = () => {
  ElMessageBox.confirm(
    "确定要取消编辑吗？所有未保存的更改将丢失。",
    "确认取消",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      emit("close");
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 初始化患者信息
const initPatientInfo = () => {
  if (props.patientInfo) {
    console.log("接收到患者信息:", props.patientInfo);

    // 直接从 props.patientInfo 中获取字段，保持与父组件传递的一致
    formData.patient_name = props.patientInfo.patient_name || "11";
    formData.patient_age = props.patientInfo.patient_age || null;
    formData.patient_gender = props.patientInfo.patient_gender || "男";
    formData.id_number = props.patientInfo.id_number || "";
    formData.visit_id = props.patientInfo.visit_id || "";
    formData.insurance_card_number =
      props.patientInfo.insurance_card_number || "";

    // 如果提供了身份证号，优先根据身份证号计算年龄和性别
    if (props.patientInfo.id_number) {
      formData.patient_gender = calculateGenderFromID(
        props.patientInfo.id_number
      );
      formData.patient_age = calculateAgeFromID(props.patientInfo.id_number);
    }
  }
};

// 生命周期
onMounted(async () => {
  // 首先初始化患者信息（适用于新建和编辑模式）
  initPatientInfo();

  // 混合方式加载数据
  await loadData();
});

// 监听 patientInfo 的变化
watch(
  () => props.patientInfo,
  (newPatientInfo) => {
    if (newPatientInfo) {
      initPatientInfo();
      // 如果患者信息变化，重新加载数据
      if (newPatientInfo.visit_id) {
        loadData();
      }
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.diagnosis-edit {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 8px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.form-section {
  margin-bottom: 20px;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.ai-analysis-block {
  margin-top: 16px;
}

.ai-content {
  white-space: pre-line;
  line-height: 1.6;
}

.ai-actions {
  margin-top: 8px;
  text-align: right;
}

.examination-orders {
  margin-top: 16px;
}

.orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.orders-header h4 {
  margin: 0;
  color: #303133;
}

.total-fee {
  font-weight: 600;
  color: #e6a23c;
  margin-right: 16px;
}

.orders-table {
  width: 100%;
}

.no-orders {
  text-align: center;
  padding: 40px 0;
}

.ai-quick-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.quick-tip {
  color: #909399;
  font-size: 14px;
}

.quick-result-section {
  margin-bottom: 12px;
}

.quick-result-section h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
}

.quick-result-section p {
  margin: 0;
  color: #606266;
  line-height: 1.5;
}

.exam-result-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.exam-info {
  margin-bottom: 24px;
}

.exam-content h4 {
  margin: 16px 0 8px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.exam-findings,
.exam-conclusion {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 16px;
  line-height: 1.6;
}

.exam-images {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.exam-image-item {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.no-images {
  color: #909399;
  text-align: center;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .diagnosis-edit {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    display: flex;
    gap: 8px;
  }

  .ai-quick-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  .exam-images {
    justify-content: center;
  }
}
</style>